//
//  GaoImageBrowserCell.m
//  DuTe
//
//  Created by Gikki Ares on 2020/12/24.
//  Copyright © 2020 vgemv. All rights reserved.
//

#import "JsImageBrowserViewCell.h"
#import "JsWebImageManager.h"

@interface JsImageBrowserViewCell()

{
UIScrollView * msv;
UIImageView * miv;
	JsImageBrowserViewCellModel * mmodel;
}
@end


@implementation JsImageBrowserViewCell

- (instancetype)init {
	if(self = [super init]) {
		[self commonInit];
	}
	return self;
}

- (instancetype)initWithFrame:(CGRect)frame {
	if(self = [super initWithFrame:frame]) {
		[self commonInit];
	}
	return self;
}



- (void)commonInit {

	msv = [UIScrollView new];
	if (@available(iOS 13.0, *)) {
		msv.automaticallyAdjustsScrollIndicatorInsets = NO;
	} else {
			// Fallback on earlier versions
	}
	[self addSubview:msv];
	
	miv = [UIImageView new];
	msv.backgroundColor = [UIColor blackColor];
	[msv addSubview:miv];
	miv.backgroundColor = [UIColor redColor];
	
	self.backgroundColor = [UIColor blackColor];
}

- (void) layoutSubviews {
	[super layoutSubviews];
	
	//不知道为什么,这个时机加了个20的contentOffset.
//	UICollectionView * cv = (UICollectionView *)self.superview;

	
	msv.frame = self.bounds;
	msv.contentOffset = CGPointMake(0, 0);
	msv.contentSize = self.bounds.size;
	UIImage * image = [self currentImage];
	if(image) {
		miv.image = image;
		miv.frame = [mmodel aspectFitFrameForImage:image inBounds:self.bounds];
	}
	else {
		[JsWebImageManager downloadImageWithUrlString:mmodel.mstr_thumbImageUrl completionHandler:^(UIImage * _Nonnull image) {
			if(image) {
				self->miv.image = image;
				self->miv.frame = [self->mmodel aspectFitFrameForImage:image inBounds:self.bounds];
			}
		}];
	}
	

}

//是否有原图,有则返回
//是否有缩略图,有则返回.
//没有返回nil
- (UIImage *)currentImage {
	UIImage * image = [[JsWebImageMemoryCache sharedInstance] imageForKey:mmodel.mstr_originImageUrl];
	if(image)  {
		return image;
	}
	image = [[JsWebImageMemoryCache sharedInstance] imageForKey:mmodel.mstr_thumbImageUrl];
	if(image)  {
		return image;
	}
	return nil;
}

-(void)setModel:(JsImageBrowserViewCellModel *)model {
	mmodel = model;
	[self setNeedsLayout];
}


@end
